package com.dcy.system.biz.component;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.dcy.common.constant.Constant;
import com.dcy.system.biz.service.RoleService;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Author：dcy
 * @Description:
 * @Date: 2021/3/29 16:02
 */
@Component
public class DataScopeUtil {

    @Autowired
    private RoleService roleService;

    /**
     * 数据过滤
     *
     * @param wrapper
     */
    public void dataScopeFilter(AbstractWrapper wrapper) {
        dataScopeFilter(wrapper, null);
    }

    /**
     * 数据过滤
     *
     * @param wrapper
     * @param deptAlias 主表别名
     */
    public void dataScopeFilter(AbstractWrapper wrapper, String deptAlias) {
        String userId = RpcContext.getContext().getAttachment(Constant.USER_ID);
        boolean allDataScopeFlag = roleService.getAllDataScopeFlag(userId);
        if (!allDataScopeFlag){
            // 有数据范围
            Set<String> dataScopeList = roleService.getDataScopeByUserId(userId);
            if (StrUtil.isNotBlank(deptAlias)) {
                wrapper.apply(StrUtil.format(" {}.dept_id in ({})", deptAlias, CollUtil.join(dataScopeList, ",", "\"", "\"")));
            } else {
                wrapper.apply(StrUtil.format(" dept_id in ({})", CollUtil.join(dataScopeList, ",", "\"", "\"")));
            }
        }
    }

}
